/* Copyright (c) 2012 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Dijkstra's_algorithm_(Java)?action=history&offset=20081113161332

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Retrieved from: http://en.literateprograms.org/Dijkstra's_algorithm_(Java)?oldid=15444
 */

package algorithme;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

import reservation.Trajet;
import serialisation.DataManager;
import data.Ville;

/**
 * Classe Dijkstra : Permet de calculer le plus court chemin sur un graphe
 * 
 * @author Alexandre Boursier and Mamadou Diallo and Cyril Gorrieri and Emmanuel
 *         Menage
 * @version 2012.01.23
 */
public class Dijkstra {
	private static Noeud[] noeuds;

	/**
	 * Calcule tous les chemins optimaux jusqu'a toutes les destinations
	 * possible
	 * 
	 * @param source
	 * @param op
	 */
	private static void calculChemins(Noeud source, Option op) {
		source.setPoidMin(0);
		PriorityQueue<Noeud> listeNoeuds = new PriorityQueue<Noeud>();
		listeNoeuds.add(source);

		while (!listeNoeuds.isEmpty()) {
			Noeud n = listeNoeuds.poll();

			// Regarde tous les chemins qui partent de n
			for (Liaison l : n.getLiaisons()) {
				Noeud v = l.getDestination();
				double poid = l.getWeight();
				double poidJusqueU = n.getPoidMin() + poid;
				if (poidJusqueU < v.getPoidMin()) {
					listeNoeuds.remove(v);

					v.setPoidMin(poidJusqueU);
					v.setPrecedent(n);
					v.setPrecedentTrajet(l.getTrajet());
					listeNoeuds.add(v);
				}
			}
		}
	}

	/**
	 * Recupère le plus court chemin debut jusqu'à cette destination
	 * 
	 * @param destination
	 * @return
	 */
	private static List<Trajet> recupererPlusCourtChemin(Noeud destination) {
		List<Trajet> path = new ArrayList<Trajet>();
		for (Noeud vertex = destination; vertex != null; vertex = vertex
				.getPrecedent()) {
			if (vertex.getPrecedentTrajet() != null)
				path.add(vertex.getPrecedentTrajet());
		}

		Collections.reverse(path);
		return path;
	}

	/**
	 * Recupère le plus court chemin entre deux ville selon une option
	 * 
	 * @param rangV1
	 *            Rang de la ville de départ
	 * @param rangV2
	 *            Rang de la ville d'arrivée
	 * @param op
	 *            Option du poids des liaison
	 * @return Le plus court chemin
	 */
	public static List<Trajet> recupererCheminOptimal(int rangV1, int rangV2,
			Option op) {
		// On initialise tous les noeuds
		Ville[] values = Ville.values();
		noeuds = new Noeud[values.length - 1];
		for (int i = 0; i < values.length - 1; i++) {
			noeuds[i] = new Noeud(values[i].toString());
		}
		for (int i = 0; i < values.length - 1; i++) {
			List<Trajet> trajets = DataManager.getTrajetsByVille(values[i]);
			List<Liaison> liaisons = new ArrayList<Liaison>();
			for (Trajet t : trajets) {
				liaisons.add(new Liaison(noeuds[t.getArrivee().getRang()], t,
						op));
			}
			noeuds[i].setLiaisons(listToTab(liaisons));
		}

		calculChemins(noeuds[rangV1], op);
		return recupererPlusCourtChemin(noeuds[rangV2]);
	}

	/**
	 * Transforme une liste en tableau
	 * 
	 * @param ls
	 *            Liste de liaisons
	 * @return Un tableau de liaison
	 */
	private static Liaison[] listToTab(List<Liaison> ls) {
		Liaison[] liaisons = new Liaison[ls.size()];
		for (int i = 0; i < ls.size(); i++) {
			liaisons[i] = ls.get(i);
		}
		return liaisons;
	}
}
